package com.neusoft.news;

import com.neusoft.news.utils.JDBCUtils;
import org.apache.catalina.Context;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.apache.tomcat.util.scan.StandardJarScanner;

import java.io.File;
//import java.util.Map;

/**
 * 内置Tomcat启动类
 *
 * @author wh
 * @ClassName: WebServer
 * @Description: 内置Tomcat启动类
 * @date 2021年5月22日
 * @since JDK 1.8
 */
public class WebServer {

    public static void main(String[] args) {
        WebServer.start();
    }

    /**
     * Tomcat 启动方法
     *
     * @Title: start
     * @Description: Tomcat 启动方法
     */
    public static void start() {
        // 读取配置文件
//        Yaml yaml = new Yaml();
//        Map<String, Map<String, Object>> load = yaml.load(WebServer.class.getClassLoader()
//                .getResourceAsStream("AppConfig.yml")
//        );
//        Map<String, Object> server = load.get("server");

        // tomcat的端口号
        int port = 8080;
//        int port = (int) server.get("port");
        // tomcat对象
        Tomcat tomcat = new Tomcat();

        tomcat.setPort(port);

        // web 工程配置
        // host 默认为localhost
        // contextPath 为在浏览器中访问项目的根路径(ip:port/{contextPath}/xx)
        // docBase 为项目中webapp 所在路径
        // tomcat.addWebapp(host, contextPath, docBase)

        String contextPath = "/";
        String docBase = "src/main/webapp";
        Context context = tomcat.addWebapp(contextPath, new File(docBase).getAbsolutePath());

        StandardJarScanner jarScanner = (StandardJarScanner) context.getJarScanner();
        jarScanner.setScanManifest(false);

        WebResourceRoot resources = new StandardRoot(context);
        // 加入WebServlet
        resources.addPreResources(
                new DirResourceSet(resources,
                        "/WEB-INF/classes",
                        new File("target/classes").getAbsolutePath(),
                        "/"));
        context.setResources(resources);

        try {
            tomcat.start();
            System.out.println("tomcat服务启动成功，端口：" + port);
            tomcat.getServer().await();
            JDBCUtils.destroy();
        } catch (Exception e) {
            System.out.println("tomcat服务启动失败");
            e.printStackTrace();
        }
    }

}